<?php

class rhRIMTask extends sfBaseTask
{
  protected function configure()
  {
    // // add your own arguments here
    // $this->addArguments(array(
    //   new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'),
    // ));

    $this->addOptions(array(
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'RadHealth Rerence Information Model'),
      // add your own options here
      
    ));

    $this->namespace        = 'rhRIM';
    $this->name             = 'load';
    $this->briefDescription = '';
    $this->detailedDescription = <<<EOF
The [rhRIM|INFO] task does things.
Call it with:

  [php symfony rhRIM|INFO]
EOF;
  }

  protected function execute($arguments = array(), $options = array())
  {
    // initialize the database connection
    //$databaseManager = new sfDatabaseManager($this->configuration);
    //$connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();

    // add your code here
    //TODO: error handling if file doesn't exist.
    $settings = sfYaml::load('config/rhrim.yml');
    // create a new array containing name of tables to be installed (tbi)
    $tbi = array(); 
    // create a new array containing name of tables to be deleted (tbd)
    $tbd = array(); 
    
    foreach($settings as $env=>$values)
    {
      //First validate that it is an acceptable value
      if (!$this->validate('versions', $env))
        throw new Exception("Environment $env is not valid.  Please check your rhrim.yml file and try again.");
          
      foreach($values as $superclass=>$table)
      {
       //Make sure required tables are added to tbi list
       if(in_array('Y', $table))
       {
         $tbi = array_merge($tbi, $this->installRequiredTables($superclass));
         //Also add lookuptables for this
         $tbi = array_merge($tbi, $this->installLookupTables($superclass, $superclass));
       }
       else
       {
         $tbd = array_merge($tbd, $this->installRequiredTables($superclass));
         $tbd = array_merge($tbd, $this->installLookupTables($superclass, $superclass));	
       }
       //Now add enabled tables	
       foreach($table as $name=>$enabled)
       {
         //Validate the name of the table given in the file
         if(!$this->validate($superclass, $name))
      	    throw new Exception("Invalid table name '$name' in your rhrim.yml file.  Please correct and try again.");
         if($enabled == 'Y')
      	 {
      	   $tbi = array_merge($tbi, array($name));
      	   $tbi = array_merge($tbi, $this->installLookupTables($superclass, $name));
      	 }
      	 else
      	 {
      	   $tbd = array_merge($tbd, array($name));
      	   $tbd = array_merge($tbd, $this->installLookupTables($superclass, $name));
      	 }
        }
      }
      print_r($tbi);
      print_r($tbd);
      // Prepare plugin directories by completely deleting them!
      $output = array();
      exec('rm -r plugins/rhRimDataModelPlugin/config/doctrine/* 2>&1'); // Schema files.
      exec('rm -r plugins/rhRimDataModelPlugin/data/fixtures/* 2>&1'); // Data files.
      exec('rm -r plugins/rhRimDataModelPlugin/lib/filter/doctrine/* 2>&1'); // Form filters.
      exec('rm -r plugins/rhRimDataModelPlugin/lib/form/doctrine/* 2>&1'); // Form files.
      exec('rm -r plugins/rhRimDataModelPlugin/lib/model/doctrine/* 2>&1'); // Model files.
      
      // Look for files in lib directory that are part of rhRIM but not tbi
      foreach($tbd as $v)
      {
        exec('rm lib/model/doctrine/rhRimDataModelPlugin/'.$v.'.class.php  2>&1'); // Schema files.
        exec('rm lib/model/doctrine/rhRimDataModelPlugin/base/Base'.$v.'.class.php  2>&1'); // Schema files.
        exec('rm lib/model/doctrine/rhRimDataModelPlugin/'.$v.'Table.class.php 2>&1'); // Schema files.
        exec('rm lib/filter/doctrine/rhRimDataModelPlugin/'.$v.'FormFilter.class.php 2>&1'); // Schema files.
        exec('rm lib/filter/doctrine/rhRimDataModelPlugin/base/Base'.$v.'FormFilter.class.php 2>&1'); // Schema files.
        exec('rm lib/form/doctrine/rhRimDataModelPlugin/'.$v.'Form.class.php 2>&1'); // Schema files.
        exec('rm lib/form/doctrine/rhRimDataModelPlugin/base/Base'.$v.'Form.class.php 2>&1'); // Schema files.
      }
      // Start loading
      foreach($tbi as $table)
      {
      	  //Get Schema File
      	  exec("cd plugins/rhRimDataModelPlugin/config/doctrine/;wget http://radhealth.googlecode.com/svn/trunk/data/rhRimDataModelPlugin/config/doctrine/".strtolower($table).".yml 2>&1");
      	  //Execute Model
      	  exec("cd plugins/rhRimDataModelPlugin/lib/model/doctrine/;wget http://radhealth.googlecode.com/svn/trunk/data/rhRimDataModelPlugin/lib/model/doctrine/Plugin$table.class.php 2>&1");
      	  exec("cd plugins/rhRimDataModelPlugin/lib/model/doctrine/;wget http://radhealth.googlecode.com/svn/trunk/data/rhRimDataModelPlugin/lib/model/doctrine/Plugin".$table."Table.class.php 2>&1");
          //Execute Form
          exec("cd plugins/rhRimDataModelPlugin/lib/form/doctrine/;wget http://radhealth.googlecode.com/svn/trunk/data/rhRimDataModelPlugin/lib/form/doctrine/Plugin".$table."Form.class.php 2>&1");
          //Execute Filter
          exec("cd plugins/rhRimDataModelPlugin/lib/filter/doctrine/;wget http://radhealth.googlecode.com/svn/trunk/data/rhRimDataModelPlugin/lib/filter/doctrine/Plugin".$table."FormFilter.class.php 2>&1");
      }
    }
  }
  private function validate($item, $value)
  {
  	$validators = sfYaml::load('plugins/rhRimDataModelPlugin/config/task_validation.yml');
  	return array_key_exists($value, $validators[$item]);
  }
  private function installRequiredTables($superclass)
  {
    $tba = array();
  	$validators = sfYaml::load('plugins/rhRimDataModelPlugin/config/task_validation.yml');
    if(!$validators[$superclass])
    {
      throw new Exception("Superclass $superclass does not exist. Fix your rhrim.yml file and try again.");	
    }
    else
    {
          foreach ($validators[$superclass] as $k => $v)
  	  {
            if($v['required'] == 'Y')
  	      $tba = array_merge($tba, array($k));
  	  }    
  	}
  	return $tba;
  }
  private function checkoutTableDefinition($table)
  {
  	
  }
  private function installLookupTables($superclass, $name)
  {
  	$tba = array();
  	$srt = sfYaml::load('plugins/rhRimDataModelPlugin/config/task_validation.yml');
  	if(is_array($srt[$superclass][$name]))
  	{
  	  foreach ($srt[$superclass][$name] as $k => $v)
  	  {
  	  	if($k == 'lookuptables')
  	  	  $tba = array_merge($tba, $v);	
  	  }
    }
    return $tba;
  }
}
